import React from 'react'
import {useState,useMemo} from 'react'
export default function Computed() {
  const [list,setList]=useState([
    {
        id:'1001',
        checked:true,
        name:'苹果',
        price:6.8,
        num:1
    },
    {
        id:'1002',
        checked:true,
        name:'草莓',
        price:16.8,
        num:1
    }

  ])
  const changeNum=(id,num)=>{
    console.log('id',id);
    console.log('num',num);
    let newList=list.map(item=>{
        if(item.id===id){
            return{
                ...item,
                num:+num
            }
        }else{
            return item
        }
    })
    setList(newList)
  }
  const switchCheck=(id,arg2)=>{
    console.log('arg2',arg2);
    let newList=list.map(item=>{
        if(item.id===id){
            return{
                ...item,
                checked:arg2
            }
        }else{
            return item
        }
    })
    console.log('newList',newList);
    setList(newList)
  }

  let totalPrice= useMemo(()=>{
    console.log('计算总价');
    return list.filter(item=>item.checked).reduce((prev,cur)=>prev+cur.price*cur.num,0)
  },[list])
  return (
    <div>
        <h1>购物车</h1>
        <table>
            <thead>
                <tr>
                    <td>编号</td>
                    <td>名称</td>
                    <td>价格</td>
                    <td>数量</td>
                    <td>小计</td>
                </tr>
            </thead>
            <tbody>
                {
                    list.map(item=><tr key={item.id}>
                        <td>
                            <input type='checkbox' checked={item.checked} onChange={(e)=>switchCheck(item.id,e.target.checked)}></input>
                        </td>
                        <td>{item.name}</td>
                        <td>{item.price}</td>
                        <td>
                            <button>-</button>
                            <input type="text" value={item.num} onChange={(e)=>changeNum(item.id,e.target.value)}/>
                            <button>+</button>
                        </td>
                        <td>{item.price*item.num}</td>
                    </tr>)
                }
            </tbody>
            <tfoot>
                <tr>
                    <td colSpan={5}>总价:{totalPrice}------总价:{totalPrice}---总价:{totalPrice}</td>
                </tr>
            </tfoot>
        </table>
    </div>
  )
}
